<script lang="ts" setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import swxDtForm from '@/components/swx-dt-form/index.vue'
import sjyglService from '@/api/sjygl'
import Fldm from '@/utils/fldm'
import { encrypt, decrypt } from '@/utils/aes'
// 定义分类代码dto
interface FldmDTO {
  dm: string
  fdm: string
  mc: string
  lbbm: string
  sm: string
  xh: string
  tbwjbh?: string
}
// 设置一个枚举
enum Gender {
  '407084100744554496' = '1101',
  '407084100744554497' = '1102',
  '407084100744554498' = '1103',
  '407084100744554499' = '1104',
}
/* 结构化数据源对应图标 */
enum ImgGender {
  '407084100744554496' = 'jghsjy',
  '407084100744554497' = 'fjghwj',
  '407084100744554498' = 'xxzjj',
  '407084100744554499' = 'gdrz',
}
// 结构化-添加数据源
const jghsjy = window.jghsjy
// 非结构化-添加数据源
const fjghsjy = window.fjghsjy
// 消息中间件-添加数据源
const xxzjjsjy = window.xxzjjsjy
// 归档日志-添加数据源
const gdrzsjy = window.gdrzsjy
// 非结构化-本地文件
const fjghbdwj = window.fjghbdwj
// 非结构化-sftp
const fjghsftp = window.fjghsftp
// 非结构化-minio
const fjghminio = window.fjghminio
// 归档日志-minio
const gdrzoracle = window.gdrzoracle
// 结构化-人大金仓
const jghsjyrdjc = window.jghsjyrdjc
// 入参
const emit = defineEmits(['handleCurrentChange'])
const sjyList = ref<FldmDTO[]>([])
// 生命周期
onMounted(async () => {
  const res = await Fldm.getFldmlb('1100')
  sjyList.value = res.map((cur: FldmDTO, index: number) => {
    cur.fdm = 1100 + index + ''
    return cur
  })
})
/*
 * 打开弹框
 */
//
const dialogVisible = ref<boolean>(false)
const isReadonly = ref<boolean>(false)
const openDialog = async (row: undefined | any, bol = false) => {
  // 修改
  if (row?.sjybh) {
    const params = {
      sjybh: row.sjybh,
    }
    const res: any = await sjyglService.getSjyxxjm(params)
    if (res.data) {
      // 这里还要判断一下如果是结构化数据的话还要截取一下Ip加端口
      try {
        res.data.ljpz = JSON.parse(decrypt(res.data.ljpzjm))
        sjyForm.value = res.data
      } catch {
        sjyForm.value = {}
      }
    }
    querySjylx()
    // 修改默认进入第二步
    step.value = 2
  } else {
    sjylxList.value = []
    // 新增
    sjyForm.value = {
      sjybh: '',
      sjymc: '',
      sjylxdm: '',
      sjylxmc: '',
      ljpz: {},
      bz: '',
      xh: '',
      ywfldm: '',
      sjyfzbh: row.sjyfzbh,
      sjyfzmc: row.sjyfzmc,
    }
    step.value = 1
  }
  isReadonly.value = bol
  dialogVisible.value = true
}
/**
 * 数据源表单数据
 */
const sjyForm = ref<any>({})
// 查询关键字
const filterText = ref('')
// 当前步骤
const step = ref<number>(1)
/*
 * 下一步
 */
const next = () => {
  /*  下一步禁用 */
  if (!sjyForm.value.ljpz || !sjyForm.value.ljpz.lxdm) {
    ElMessage.warning('请选择类型!')
    return
  }
  step.value = 2
}
/* 测试 */
const test = () => {
  const params = {
    sjylxdm: sjyForm.value.sjylxdm,
    lxdm: sjyForm.value.ljpz.lxdm,
    ljpz: encrypt(
      JSON.stringify({
        ...sjyForm.value.ljpz,
        lxmc: sjyForm.value.ljpz.lxmc.replace('归档', ''),
      }),
    ),
  }
  sjyglService
    .testWbsjylj(params)
    .then((res) => {
      if (res.data) {
        ElMessage({
          message: '测试通过',
          type: 'success',
          showClose: true,
        })
      } else {
        ElMessage({
          message: '测试不通过',
          type: 'error',
          showClose: true,
        })
      }
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
}

const labelWidth = ref<string>('140px')
// 表单类型
const formList = computed(() => {
  let arr: any = []
  switch (sjyForm.value.sjylxdm) {
    // 结构化
    case '407084100744554496':
      arr = '407084100744554665,407084100744554503'.includes(sjyForm.value.ljpz?.lxdm)
        ? jghsjyrdjc
        : jghsjy
      break
    case '407084100744554497':
      // 非结构化
      arr = getFjghlx()
      break
    // 消息中间件
    case '407084100744554498':
      arr = xxzjjsjy
      break
    case '407084100744554499':
      // 归档日志
      arr = getFjghlx()
      break
    default:
      break
  }
  return arr
})
const getFjghlx = () => {
  let arr: any = []
  switch (sjyForm.value.ljpz?.lxdm) {
    // 非结构化-本地文件
    case '407084100744554506':
      arr = fjghbdwj
      break
    // 非结构化-sftp
    case '407084100744554507':
      // 非结构化
      arr = fjghsftp
      break
    // 非结构化-minio
    case '407084100744554508':
      arr = fjghminio
      break
    case '407084100744554509':
      // 归档
      arr = fjghsjy
      break
    case '407084100744554510':
      // 归档
      arr = fjghsjy
      break
    case '407084100744554513':
      // 归档
      arr = gdrzoracle
      break
    default:
      arr = sjyForm.value.sjylxdm === '407084100744554499' ? gdrzsjy : []
      break
  }
  return arr
}
/* 初始化表单 */
const initFormValue = () => {
  // 初始化表单
  let temp: any = {}
  formList.value?.map((cur: any) => {
    temp[cur.value] = cur.multiple ? [] : ''
    if (cur.labelValue) {
      temp[cur.labelValue] = cur.multiple ? [] : ''
    }
  })
  sjyForm.value.ljpz = {
    ...temp,
    lxdm: sjyForm.value.ljpz.lxdm,
    lxmc: sjyForm.value.ljpz.lxmc,
  }
}

/*
 * 上一步
 */
const last = () => {
  // 考虑要不要清空表单
  step.value = 1
}

/**
 * 查询数据源那类型
 */
const sjylxList = ref<any>([])
const querySjylx = async () => {
  const res = await Fldm.getFldmlb(Gender[sjyForm.value.sjylxdm as keyof typeof Gender])
  sjylxList.value = res.filter((cur: any) => {
    return cur.mc.includes(filterText.value)
  })
}

// 数据源分类选中
const changeSjyfl = (item: any) => {
  if (sjyForm.value.sjylxdm === item.dm) {
    return
  }
  sjyForm.value.sjylxdm = item.dm
  sjyForm.value.sjylxmc = item.mc
  filterText.value = ''
  sjyForm.value.ljpz.lxdm = ''
  querySjylx()
}

// 数据类型选中
const changeSjylx = (item: any) => {
  if (sjyForm.value.ljpz.lxdm === item.dm) {
    return
  }
  initFormValue()
  sjyForm.value.ljpz.lxdm = item.dm
  sjyForm.value.ljpz.lxmc = item.mc
  sjyForm.value.tbwjdz = item.tbwjbh
}
/**
 * 表单提交
 */
const formRef = ref()
// 表单校验
const confrim = async () => {
  // 表单校验
  const res: boolean | object | any = await formRef.value.validateForm()

  if (res) {
    // 检验成功，赋值
    sjyForm.value.ljpz = res
    sjyForm.value.sjymc = res.sjymc
    sjyForm.value.ljpz.lxmc = res.lxmc.replace('归档', '')
    // 调用保存接口
    saveSjy()
  }
}
/* 保存数据源 */
const saveSjy = () => {
  const params = {
    ...sjyForm.value,
    ljpz: encrypt(JSON.stringify(sjyForm.value.ljpz)),
  }
  sjyglService
    .saveSjy(params)
    .then(() => {
      ElMessage.success('保存成功！')
      dialogVisible.value = false
      emit('handleCurrentChange', 1)
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
}
// 弹窗标题
const title = computed(() => {
  return step.value === 1 ? '创建数据源' : '设置数据源参数'
})
// 弹窗宽度
const dialogWidth = computed(() => {
  return '820px'
})
// 引入图片
const requreImgPath = (dm: string) => {
  try {
    return new URL(
      `/src/assets/img/sjygl/${ImgGender[dm as keyof typeof ImgGender]}.png`,
      import.meta.url,
    ).href
  } catch (error) {
    console.log(error, 'error')
  }
}
// 引入图片
const reloadImg = (dm: string) => {
  if (!dm) {
    return
  }
  try {
    return new URL(`/src/assets/images/default/${dm}.png`, import.meta.url).href
  } catch (error) {
    console.log(error, 'error')
  }
}
defineExpose({ openDialog })
</script>
<template>
  <el-drawer
    :title="title"
    v-model="dialogVisible"
    :close-on-click-modal="false"
    :size="dialogWidth"
    append-to-body
  >
    <div class="content">
      <!-- 第一步 -->
      <div class="step" v-if="step === 1">
        <!-- 数据源分类 -->
        <div class="sjyfl">
          <div
            v-for="item in sjyList"
            :key="item.dm"
            class="sjyfl-item"
            :class="{ 'active-sjyfl': sjyForm.sjylxdm === item.dm }"
            @click="changeSjyfl(item)"
          >
            <img :src="requreImgPath(item.dm)" class="sjyfl-item-img" />
            <span>{{ item.mc }}</span>
          </div>
        </div>
        <div class="sjyfl-children">
          <!-- 查询条件 -->
          <el-input
            class="filter-input input-search"
            v-model="filterText"
            placeholder="请输入查询关键字"
            maxlength="30"
            :suffix-icon="Search"
          />
          <el-button type="primary" color="#617d98" @click="querySjylx">查询</el-button>
          <!-- 数据源类型 -->
          <div class="sjylx">
            <div
              v-for="item in sjylxList"
              :key="item.dm"
              :class="{ 'active-sjylx': sjyForm.ljpz.lxdm === item.dm }"
              class="sjylx-item"
              @click="changeSjylx(item)"
            >
              <div class="img-wrapper">
                <img :src="reloadImg(item.tbwjbh)" class="sjylx-item-img" />
              </div>
              <span class="sjylx-item-span">{{ item.mc }}</span>
            </div>
          </div>
        </div>
      </div>
      <!-- 第二步 -->
      <div v-if="step === 2">
        <el-form :form="sjyForm" :labelWidth="labelWidth" label-position="right" inline>
          <el-form-item label="数据源分类：" class="flex-form-item">
            <el-input v-model="sjyForm.sjylxmc" disabled></el-input>
          </el-form-item>
          <el-form-item label="数据源类型：" class="flex-form-item flex-form-right">
            <div class="img-wrapper">
              <img :src="reloadImg(sjyForm.tbwjdz)" class="sjylx-item-img" />
            </div>
            <span class="sjyfl-item-span">{{ sjyForm.ljpz.lxmc }}</span>
          </el-form-item>
        </el-form>
        <!-- 表单使用 -->
        <swx-dt-form
          ref="formRef"
          v-model:form-value="sjyForm.ljpz"
          :form-list="formList"
          :isReadonly="isReadonly"
          :label-width="labelWidth"
        />
      </div>
    </div>
    <template #footer>
      <div style="flex: auto">
        <el-button type="info" plain @click="dialogVisible = false">取消</el-button>

        <el-button type="success" v-if="step === 1" @click="next">下一步</el-button>
        <el-button type="success" v-else-if="step === 2 && !isReadonly" @click="last"
          >上一步</el-button
        >
        <el-button type="primary" v-if="step === 2 && !isReadonly" @click="test"
          >一键测试</el-button
        >
        <el-button type="primary" v-if="step === 2 && !isReadonly" @click="confrim">确定</el-button>
      </div>
    </template>
  </el-drawer>
</template>
<style lang="scss" scoped>
.content {
  height: 450px;
  .step {
    width: 100%;
    height: 100%;
  }
  .sjyfl,
  .sjyfl-children {
    padding: 20px;
    background-color: rgba($color: var(--table-th-bg), $alpha: 0.4);
    border-radius: 3px;
    height: 161px;
    border: solid 1px var(--border-color);
    .sjyfl-item {
      width: 118px;
      height: 118px;
      display: flex;
      flex-direction: column;
      border-radius: 4px;
      align-items: center;
      float: left;
      margin-left: 23px;
      background-color: var(--menu-top-color-default);
      border: 1px solid var(--border-color);
      cursor: pointer;
      &.active-sjyfl,
      &:hover {
        border-color: var(--btn-bg-default);
        background-color: var(--blue-background-color);
      }
    }
    .sjyfl-item-img {
      width: 52px;
      height: 52px;
      margin: 23px 0 10px 0;
    }
  }
  .sjyfl-children {
    height: 291px;
    margin-top: 10px;
  }
  .filter-input {
    width: 300px;
    margin-right: 10px;
  }
  .sjylx {
    height: 120px;
    padding: 10px 0px;
    .sjylx-item {
      width: 115px;
      height: 100px;
      margin-bottom: 10px;
      border: 1px solid var(--border-color);
      display: flex;
      padding: 10px 13px;
      border-radius: 3px;
      flex-direction: column;
      align-items: center;
      float: left;
      cursor: pointer;
      & + .sjylx-item {
        margin-left: 10px;
      }
      &:nth-child(7n) {
        margin-left: 0;
      }
      &.active-sjylx,
      &:hover {
        background-color: var(--blue-background-color);
        border-color: var(--btn-bg-default);
      }
    }
  }
  .sjyfl-item-span {
    display: block;
    text-align: center;
    height: 20px;
    line-height: 20px;
    overflow: hidden;
  }
  .img-wrapper {
    width: 45px;
    height: 45px;
    display: inline-block;
  }
  .sjylx-item-img {
    width: 100%;
    height: 100%;
  }
  .sjylx-item-span {
    margin-top: 10px;
  }
  .flex-form-item {
    width: calc(100% - 264px);
    margin-right: 0 !important;
    align-items: center;
    &.flex-form-right {
      width: 250px;
      :deep(.ep-form-item__content) {
        flex-direction: column;
      }
    }
  }
  .ep-button {
    min-width: 65px;
  }
}
</style>
